package com.shiguiwu.springboot3.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.shiguiwu.springboot3.interceptor.SqlAdapterInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description: mybatis工具类
 * @author: stone
 * @date: Created by 2023/7/19 22:52
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.util
 */
@Slf4j
public class MybatisUtil {

    /**
     * 关键字缓存
     */
    public static Map<String, Set<String>> DATABASE_KEYWORDS_CACHE = new ConcurrentHashMap<>(4);

    /**
     * 处理sql,根据不同的数据库给字段关键字添加包裹符号
     * @param sql
     * @param cols
     * @param dataSource
     * @param databaseId
     * @return
     * @throws SQLException
     */
    public static String processSql(String sql, DataSource dataSource, String databaseId, Set<String> cols) throws SQLException {

        // 使用正则表达式匹配多个连续的空格，并替换为单个空格
        sql = sql.replaceAll("\\s+", " ");

        if (CollUtil.isEmpty(cols)) {
            return sql;
        }

        for (String col : cols) {
            if (isKeyword(col, databaseId, dataSource)) {
                String replacement = getReplacement(col, databaseId);
                sql = sql.replaceAll(col, replacement);
            }
        }
        //去掉多余的添加符号,因为就是可能写sql的自己会加上`name`,如果这里还加一次，就两层，所有只保留一个
        return sql.replaceAll("\"+", "\"").replaceAll("`+", "`");
    }


    /**
     * 判断是否是关键字
     * @param field 表字段
     * @return
     * @throws SQLException
     */
    public static boolean isKeyword(String field, String databaseId, DataSource dataSource) throws SQLException {
        Set<String> sqlKeywords = DATABASE_KEYWORDS_CACHE
                .computeIfAbsent(databaseId, k -> CollUtil.newHashSet(getDataKeywords(dataSource).split(",")));
        return sqlKeywords.stream().anyMatch(field::equalsIgnoreCase);
    }

    /**
     * 根据数据库类型，包裹不同的符号
     * @param field
     * @param databaseId
     * @return
     * @throws SQLException
     */
    public static String getReplacement(String field, String databaseId) throws SQLException {
        log.debug("数据库id ==> {}", databaseId);
        if (!"mysql".equalsIgnoreCase(databaseId)) {
            return "\"" + field.toUpperCase() + "\"";
        } else {
            return "`" + field + "`";
        }
    }

    /**
     * 获取数据库对于的关键字
     * @param dataSource
     * @return
     * @throws SQLException
     */
    public static String getDataKeywords(DataSource dataSource) {
        // 获取Connection对象
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            // 获取DatabaseMetaData对象
            DatabaseMetaData metaData = connection.getMetaData();

            return metaData.getSQLKeywords();
        } catch (SQLException e) {
            log.error("连接获取异常 ==> {}", e.getMessage());
        } finally {
            // 关闭Connection和SqlSession
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                log.error("连接获取异常 ==> {}", e.getMessage());
            }
        }
        return String.join(",", "SELECT","FROM");
    }

    /**
     * 包装sql后，重置到invocation中
     * @param invocation
     * @param sql
     * @throws SQLException
     */
    public static void resetSql2Invocation(Invocation invocation, String sql) throws SQLException {
        final Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(boundSql));
        MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
        msObject.setValue("sqlSource.boundSql.sql", sql);
        args[0] = newStatement;
    }

    /**
     * 重新构建MappedStatement
     * @param ms
     * @param newSqlSource
     * @return
     */
    public static MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder =
                new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }


    // 定义一个内部辅助类，作用是包装sq
    static class BoundSqlSqlSource implements SqlSource {
        private final BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }

}
